import router from '@/router';

const tagsView = {
  state: {
    tagviews: [
      {
        id: 1,
        menuName: '首页',
        menuKey: null,
        icon: 'el-icon-menu',
        router: '/backstage/home',
        superiorMenu: 0,
        sortNumber: 1,
        createName: 'system',
        createTime: '2022-11-07 17:34:18',
        updateName: 'system',
        updateTime: '2022-11-07 17:34:47',
        componentName: 'Home',
        subMenus: [],
      },
    ],
    activePath: '/backstage/home',
  },
  mutations: {
    // 设置当前激活的路由
    setActivePath(state, payload) {
      state.activePath = payload;
    },
    addTagview(state, payload) {
      // 点击左侧菜单增加tagview标签,如果存在就不插入
      let result = state.tagviews.findIndex(
        (item) => item.menuName === payload.menuName
      );
      result === -1 ? state.tagviews.push(payload) : '';
    },
    // 点击tag标签
    chooseTagview(state, payload) {
      // console.log(state.activePath);
      if (state.activePath != payload) {
        router.push(payload);
        state.activePath = payload;
      }
    },
    // 关闭tag标签
    closeTagview(state, payload) {
      // 判断当前路由
      if (payload != state.activePath) {
        // 不在同个路由
        let result = state.tagviews.findIndex(
          (item) => item.router === payload
        );
        state.tagviews.splice(result, 1);
      } else {
        // 关闭当前路由并跳转到别的路由
        let len = state.tagviews.length;
        // 需要关闭的路由数组中的下标
        let result = state.tagviews.findIndex(
          (item) => item.router === payload
        );
        // 关闭路由
        state.tagviews.splice(result, 1);
        if (state.tagviews.length === 1) {
          // 路由数组只剩一项时
          state.activePath = state.tagviews[0].router;
          router.push(state.activePath);
        } else {
          state.activePath = state.tagviews[len - 2].router;
          router.push(state.activePath);
        }
      }
    },
  },
  actions: {},
};

export default tagsView;
